package org.naxx.security.function;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.naxx.security.util.Assert;
import org.naxx.security.util.FileSystemUtil;

/**
 * Loads function types definitions from properties file.
 * This enables us to later extend function domain with 
 * custom functions.<p>
 * 
 * TODO to be removed
 */
@Deprecated
public final class FunctionTypeLoader {

	/**
	 * Loads functions from relative file system path 
	 * <i>resources/function/functions.properties</i>.
	 * 
	 * @throws IllegalStateException in case functions could not be loaded from
	 * <i>.properties</i> file
	 */
	public Set<FunctionType> load() {
		Set<FunctionType> result = new HashSet<FunctionType>();
		File file = new File("resources/function/functions.properties");
		Assert.assertFileExistsAndReadable(file);
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			while ((line = reader.readLine()) != null) {
				FunctionType descriptor = new FunctionType(line.trim());
				if(!result.add(descriptor)) {
					throw new IllegalStateException("Duplicate function definition with id '" + descriptor.getUri() + "'");
				}
			}
		} catch (IOException e) {
			throw new IllegalStateException("Unable to load functions from properties file '" 
					+ file.getAbsolutePath() + "'");
		} finally {
			FileSystemUtil.close(reader);
		}
		return result;
	}
}
